package main

import (
	"fmt"
	"github.com/streadway/amqp"
	"log"
	"sync"
)

func main() {
	// 连接RabbitMQ服务器
	conn, err := amqp.Dial("amqp://guest:guest@127.0.0.1:5672/")
	failOnError(err, "RabbitMQ 连接错误")
	defer conn.Close()
	//// 创建一个channel
	//ch, err := conn.Channel()
	//failOnError(err, "打开通道失败")
	//defer ch.Close()
	//
	//q, err := ch.QueueDeclare(
	//	"ips", // name
	//	false, // durable
	//	false, // delete when unused
	//	false, // exclusive
	//	false, // no-wait
	//	nil,   // arguments
	//)
	failOnError(err, "未能声明队列")
	var wg sync.WaitGroup
	//var list []string
	for i := 0; i <= 255; i++ {
		// 创建一个channel
		ch, err := conn.Channel()
		failOnError(err, "打开通道失败")
		defer ch.Close()

		q, err := ch.QueueDeclare(
			"ips", // name
			false, // durable
			false, // delete when unused
			false, // exclusive
			false, // no-wait
			nil,   // arguments
		)
		failOnError(err, "未能声明队列")
		go func(i int) {
			for j := 0; j <= 255; j++ {
				go func(j int) {
					for k := 0; k < 255; k++ {
					//	go func(k int) {
						for l := 0; l < 255; l++ {
							wg.Add(1)

							IP := fmt.Sprintf("%v.%v.%v.%v", i, j, k, l)
							//list = append(list, IP)
							//fmt.Print(len(list),"\n")

							//ips.CreateTime = time.Now().Unix()
							//id, _ := uuid.NewUUID()
							//ips.ID = id.String()
							err = ch.Publish(
								"",     // exchange
								q.Name, // routing key
								false,  // mandatory
								false,  // immediate
								amqp.Publishing{
									ContentType: "text/plain",
									Body:        []byte(IP),
								})
							failOnError(err, "无法发布消息")
							log.Printf(" [x] Sent %s", IP)
						}
						//}(k)

					}
				}(j)

			}
		}(i)
	}
	wg.Wait()

}

// 帮助函数检测每一个amqp调用
func failOnError(err error, msg string) {
	if err != nil {
		log.Fatalf("%s: %s", msg, err)
	}
}
